package com.dolphin.aiagentplatform.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dolphin.aiagentplatform.ai.config.ChatStorageConfig;
import com.dolphin.aiagentplatform.ai.message.MessageVO;
import com.dolphin.aiagentplatform.mapper.ChatMessageMapper;
import com.dolphin.aiagentplatform.model.entity.ChatMessage;
import com.dolphin.aiagentplatform.service.ChatMessageService;
import com.dolphin.aiagentplatform.service.ChatSessionService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.messages.AssistantMessage;
import org.springframework.ai.chat.messages.Message;
import org.springframework.ai.chat.messages.SystemMessage;
import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 聊天消息服务实现类
 */
@Service
@Slf4j
public class ChatMessageServiceImpl extends ServiceImpl<ChatMessageMapper, ChatMessage>
        implements ChatMessageService {

    @Resource
    private ChatMemory chatMemory;

    @Resource
    private ChatStorageConfig chatStorageConfig;

    @Resource
    @Lazy
    private ChatSessionService chatSessionService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveChatMessage(String chatId, Long userId, String role, String content, String modelType) {
        // 不管是哪种存储方式，都更新会话的最后消息时间
        chatSessionService.updateLastMessageTime(chatId);

        try {
            // 获取当前聊天的消息数量，作为新消息的order
            int messageOrder = getChatMessageCount(chatId);

            // 构建消息对象
            ChatMessage chatMessage = new ChatMessage();
            chatMessage.setChatId(chatId);
            chatMessage.setUserId(userId);
            chatMessage.setRole(role);
            chatMessage.setContent(content);
            chatMessage.setModelType(modelType);
            chatMessage.setMessageOrder(messageOrder);
            chatMessage.setTokenCount(0); // 默认为0，实际项目中可能需要计算token数量

            // 保存消息
            boolean result = save(chatMessage);

            // 打印日志
            if (result) {
                log.debug("保存聊天消息成功，chatId: {}, role: {}, messageOrder: {}", chatId, role, messageOrder);
            } else {
                log.error("保存聊天消息失败，chatId: {}, role: {}", chatId, role);
            }

            return result;
        } catch (Exception e) {
            log.error("保存聊天消息异常", e);
            return false;
        }
    }

    @Override
    public List<Message> getChatMessagesByChatId(String chatId) {
        // 从数据库获取消息列表
        List<ChatMessage> chatMessages = lambdaQuery()
                .eq(ChatMessage::getChatId, chatId)
                .eq(ChatMessage::getIsDelete, 0)
                .orderByAsc(ChatMessage::getMessageOrder)
                .list();

        // 转换为Spring AI的Message对象
        List<Message> messages = new ArrayList<>();
        for (ChatMessage chatMessage : chatMessages) {
            String role = chatMessage.getRole();
            String content = chatMessage.getContent();

            if ("system".equals(role)) {
                messages.add(new SystemMessage(content));
            } else if ("user".equals(role)) {
                messages.add(new UserMessage(content));
            } else if ("assistant".equals(role)) {
                messages.add(new AssistantMessage(content));
            }
        }

        return messages;
    }

    @Override
    public List<MessageVO> getChatMessageVOsByChatId(String chatId) {
        // 直接从数据库获取消息列表
        List<ChatMessage> chatMessages = lambdaQuery()
                .eq(ChatMessage::getChatId, chatId)
                .eq(ChatMessage::getIsDelete, 0)
                .orderByAsc(ChatMessage::getMessageOrder)
                .list();

        // 将ChatMessage转换为MessageVO，保留创建时间
        return chatMessages.stream()
                .map(chatMessage -> {
                    MessageVO messageVO = new MessageVO();
                    messageVO.setRole(chatMessage.getRole());
                    messageVO.setContent(chatMessage.getContent());
                    messageVO.setCreateTime(chatMessage.getCreateTime());
                    return messageVO;
                })
                .collect(Collectors.toList());
    }

    @Override
    public int getChatMessageCount(String chatId) {
        // 查询数据库中的消息数量
        return Math.toIntExact(lambdaQuery()
                .eq(ChatMessage::getChatId, chatId)
                .eq(ChatMessage::getIsDelete, 0)
                .count());
    }
    
    @Override
    public int getConversationCount(String chatId) {
        // 获取所有消息并按createTime排序
        List<ChatMessage> messages = lambdaQuery()
                .eq(ChatMessage::getChatId, chatId)
                .eq(ChatMessage::getIsDelete, 0)
                .orderByAsc(ChatMessage::getCreateTime)
                .list();
                
        // 按完整对话(system+user+assistant)分组计数
        int count = 0;
        boolean hasSystem = false;
        boolean hasUser = false;
        boolean hasAssistant = false;
        
        for (ChatMessage msg : messages) {
            switch (msg.getRole()) {
                case "system": hasSystem = true; break;
                case "user": hasUser = true; break;
                case "assistant": hasAssistant = true; break;
            }
            
            // 当一组完整对话完成时计数
            if (hasUser && hasAssistant) {
                count++;
                hasSystem = hasUser = hasAssistant = false;
            }
        }
        
        return count;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteChatMessages(String chatId) {
        // 逻辑删除聊天消息
        boolean result = lambdaUpdate()
                .eq(ChatMessage::getChatId, chatId)
                .set(ChatMessage::getIsDelete, 1)
                .update();

        if (result) {
            log.debug("删除聊天消息成功，chatId: {}", chatId);
        } else {
            log.error("删除聊天消息失败，chatId: {}", chatId);
        }

        return result;
    }
}




